package com.alinesno.cloud.base.boot.service.impl;

import java.util.HashSet;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.alinesno.cloud.base.boot.entity.ManagerAccountEntity;
import com.alinesno.cloud.base.boot.entity.ManagerSettingsEntity;
import com.alinesno.cloud.base.boot.enums.RolePowerTypeEnmus;
import com.alinesno.cloud.base.boot.repository.ManagerAccountRepository;
import com.alinesno.cloud.base.boot.service.IManagerAccountService;
import com.alinesno.cloud.base.boot.service.IManagerRoleService;
import com.alinesno.cloud.base.boot.service.IManagerSettingsService;
import com.alinesno.cloud.common.core.service.impl.IBaseServiceImpl;
import com.alinesno.cloud.common.facade.pageable.DubboPageImpl;
import com.alinesno.cloud.common.facade.pageable.DubboPageRequest;
import com.alinesno.cloud.common.facade.wrapper.RestWrapper;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author WeiXiaoJin
 * @since 2018-12-16 17:53:19
 */
@Service
public class ManagerAccountServiceImpl extends IBaseServiceImpl<ManagerAccountEntity, String>
		implements IManagerAccountService {

	// 日志记录
	private static final Logger log = LoggerFactory.getLogger(ManagerAccountServiceImpl.class);
	
	// 默认key
	private static final String REGISTER_DEFAULT_APPLICATION = "sys.regist.default.application" ; 
	private static final String REGISTER_DEFAULT_ROLE = "sys.regist.default.role" ; 
	private static final String REGISTER_DEFAULT_NAME = "sys.regist.default.name" ; 

	@Autowired
	private ManagerAccountRepository managerAccountRepository;

	@Autowired
	private IManagerSettingsService managerSettingsService;

	@Autowired
	private IManagerRoleService managerRoleService;

	@Override
	public ManagerAccountEntity findByLoginName(String loginName) {
		log.debug("login name:{}", loginName);
		ManagerAccountEntity account =  managerAccountRepository.findByLoginName(loginName);
		Assert.notNull(account , "账号查询为空.");
		
		account.setPermission(this.findPermissions(account));
		account.setRole(this.findRoles(account));
		
		return account ; 
	}

	@Override
	public boolean resetPassword(String userId, String newPassword, String oldPassword) {

		Assert.hasLength(newPassword, "用户新密码不能为空.");
		Assert.hasLength(oldPassword, "用户旧密码不能为空.");

		managerAccountRepository.updateManagerAccountPassword(newPassword, userId);
		return true;
	}

	@Override
	public boolean registAccount(String loginName, String password, String phoneCode) {

		ManagerAccountEntity a = managerAccountRepository.findByLoginName(loginName) ; 
		if (a != null) {
			Assert.isTrue(false, "登陆名【" + loginName + "】已存在.");
		}

		// 获取默认值
		ManagerSettingsEntity settings = managerSettingsService.queryKey(REGISTER_DEFAULT_APPLICATION, null);
		ManagerSettingsEntity role = managerSettingsService.queryKey(REGISTER_DEFAULT_ROLE, null);
		ManagerSettingsEntity name = managerSettingsService.queryKey(REGISTER_DEFAULT_NAME, null);

		Assert.notNull(settings, "默认应用不能为空.");
		Assert.notNull(role, "默认角色不能为空.");
		Assert.notNull(name, "默认用户名不能为空.");

		ManagerAccountEntity e = new ManagerAccountEntity();

		e.setApplicationId(settings.getConfigValue());
		e.setRoleId(role.getConfigValue());

		e.setName(name.getConfigValue());

		e.setLoginName(loginName);
		e.setPassword(password);
		e.setPassword(password);
		e.setRolePower(RolePowerTypeEnmus.ROLE_TENANT.value);

		e = jpa.save(e);

		// 用户授权
		managerRoleService.authAccount(e, role.getConfigValue());

		return e == null ? false : true;
	}

	@Override
	public boolean isAdmin(ManagerAccountEntity dto) {
		Assert.notNull(dto, "账户实体信息不能为空.");
		return RolePowerTypeEnmus.ROLE_ADMIN.value.equals(dto.getRolePower()) ? true : false;
	}

	@Override
	public Set<String> findRoles(ManagerAccountEntity dto) {
		Set<String> role = new HashSet<String>() ; 
	
		// TODO 待处理用户角色问题
		role.add("admin") ; 
		
		return role ;
	}

	/**
	 * 查询所有操作权限,Shiro为我们定义了一个抽象的权限描述字串：<br/>
	 * [资源]:[模块]:[操作] ===> 如: sys:user:add
	 */
	@Override
	public Set<String> findPermissions(ManagerAccountEntity dto) {
		Set<String> permission = new HashSet<String>() ; 
		
		permission.add("sys:user:add") ; 
		
		return permission;
	}

	@Override
	public void updateAvator(String path , String id) {
		Assert.hasLength(path, "路径不能为空.");
		Assert.hasLength(id , "主键不能为空.");
		
		ManagerAccountEntity e = findEntityById(id) ; 
		e.setAvatorPath(path);
		
		this.update(e);
	}

	@Override
	public boolean checkEmailUnique(String email, String userId) {
		Assert.hasLength(email , "邮箱不能为空.");
		
		ManagerAccountEntity e = managerAccountRepository.findByEmail(email);
		
		if (e != null && e.getId() != userId) {
            return false ;
        }		
		return true ; 
	}

	@Override
	public boolean checkPhoneUnique(String phone, String userId) {
		Assert.hasLength(phone , "手机号不能为空.");
		
		ManagerAccountEntity e = managerAccountRepository.findByPhone(phone);
		
		if (e != null && e.getId() != userId) {
            return false ;
        }		
		return true ; 
	}

	@Override
	public Page<ManagerAccountEntity> findRoleMemberPage(String roleId , RestWrapper restWrapper) {
		
		restWrapper.toSpecification();
		DubboPageRequest pageable = DubboPageRequest.of(restWrapper.getPageNumber(), restWrapper.getPageSize());
		
		Page<ManagerAccountEntity> page = managerAccountRepository.findRoleMemberByPage(roleId , pageable) ; 
		DubboPageImpl<ManagerAccountEntity> dubboPage = new DubboPageImpl<ManagerAccountEntity>(page.getContent(), pageable, page.getTotalElements());
		
		return dubboPage ; 
	}
	
}
